package com.kuang.controller;

import com.kuang.dao.DepartmentDao;
import com.kuang.dao.EmployeeDao;
import com.kuang.pojo.Department;
import com.kuang.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collection;

@Controller
public class EmployeeController {

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private DepartmentDao departmentDao;

    @RequestMapping("/emps")
    public String getAllEmployees(Model model){
        Collection<Employee> employees = employeeDao.getAllEmployees();
        model.addAttribute("emps",employees);
        return "emps/list";
    }


    /**
     *  跳转到增加页面
     * @param model
     * @return
     */
    @GetMapping("/addemp")
    public String toAdd(Model model){
        Collection<Department> departments = departmentDao.getAllDepartments();
        model.addAttribute("deps",departments);
        return "emps/addEmp";
    }

    /**
     *  增加用户信息
     * @param employee
     * @return
     */
    @PostMapping("/addemp")
    public String addEmployee(Employee employee){
        System.out.println("==============="+employee);
        employeeDao.addEmployee(employee);
        return "redirect:/emps";
    }

    /**
     *  跳转到修改页面 并且携带员工信息
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/updemp/{id}")
    public String tdUpd(@PathVariable("id")Integer id,Model model){
        //通过id查询员工信息 并且返还给修改页面
        Employee employee = employeeDao.getEmployeeById(id);

        //查询全部的部门信息
        Collection<Department> departments = departmentDao.getAllDepartments();

        model.addAttribute("employee",employee);
        model.addAttribute("deps",departments);
        return "emps/updateEmp";
    }

    @PostMapping("/updemp")
    public String updEmployee(Employee employee){
        System.out.println("upd============"+employee);
        employeeDao.addEmployee(employee);
        return "redirect:/emps";
    }

    @RequestMapping("/delemp/{id}")
    public String delEmployee(@PathVariable("id")Integer id){
        employeeDao.delEmployeeById(id);
        return "redirect:/emps";
    }


}
